//
//  ViewController.m
//  NSSecureCodingDemoo
//
//  Created by hpkj on 2020/1/19.
//

#import "ViewController.h"
#import "MyDog.h"

#import "NSKeyedArchiver+ConvertNSData.h"
#import "NSKeyedUnarchiver+ConvertNSData.h"

@interface ViewController ()
@property (nonatomic,strong) NSData *archiveData;
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
}

- (IBAction)dogToData:(id)sender {
//    myDog to nsdata
    NSData * data = [NSMutableData data];

    MyDog * dog = [[MyDog alloc] init];
    dog.name = @"泰迪";
    dog.age= 2;
    NSError *error = nil;
    data = [NSKeyedArchiver archivedDataWithRootObject:dog requiringSecureCoding:YES error:&error];
    
    if (data == nil || error) {
        NSLog(@"%@",error);
        return;
    }
    _archiveData = [data copy];
    
}

- (IBAction)dataToDog:(id)sender {
    
//    data -> mydog
    NSError * error = nil;
    MyDog * dog = [NSKeyedUnarchiver unarchivedObjectOfClass:[MyDog class] fromData:_archiveData error:&error];
    NSLog(@"%@",dog.name);
    NSLog(@"%ld",dog.age);
}



- (IBAction)cateDogToData:(id)sender {
    MyDog * dog = [[MyDog alloc] init];
    dog.name = @"泰迪";
    dog.age= 2;
    _archiveData = [NSKeyedArchiver dataWithCustomClass:dog];
}

- (IBAction)cateDataToDog:(id)sender {
    MyDog * dog = (MyDog *)[NSKeyedUnarchiver customInstanceFromData:_archiveData ForClass:[MyDog class]];
    NSLog(@"%@",dog.name);
    NSLog(@"%ld",dog.age);
}



@end


